<template>
  <div class="edit-box">
    <inp-val-format v-model:formatValue="batchValue"></inp-val-format>
    <el-button
      type="primary"
      :icon="CirclePlus"
      @click="batchAdd"
    >
      批量新增
    </el-button>
    <el-button
      type="warning"
      :icon="Edit"
      @click="batchEdit"
    >
      批量修改
    </el-button>
    <p class="edit-tips">注: 只能修改分区名称和国家2列，国家请输入中文！其他数据会在保存后更新</p>
    <div class="btns-box">
      <el-button type="primary" @click="handleAdd">新增</el-button>
      <el-button
        type="danger"
        :icon="Delete"
        :loading="deleteMoreLoading"
        :disabled="multiple"
        @click="handleDelete"
      >
        批量删除
      </el-button>
    </div>
    <el-table
      v-loading="tableLoading"
      :data="tableData"
      max-height="400px"
      @selection-change="handleSelectionChange"
    >
      <el-table-column align="center" type="selection"></el-table-column>
      <el-table-column align="center" label="分区名称" prop="name"></el-table-column>
      <el-table-column align="center" label="国家代码" prop="countryCode"></el-table-column>
      <el-table-column
        align="center"
        label="方案类型"
        prop="planTypeId"
        :formatter="playTypeFormatter"
      ></el-table-column>
      <el-table-column align="center" label="国家中文名称" prop="countryName"></el-table-column>
      <el-table-column align="center" label="国家英文名称" prop="countryNameEn"></el-table-column>
      <el-table-column align="center" label="操作" width="200">
        <template #default="{row}">
          <el-button text type="primary" @click="handleUpdate()">修改</el-button>
          <el-divider direction="vertical" class="divider-margin" />
          <el-button
            text
            type="primary"
            @click="handleDelete(row)"
          >
            删除
          </el-button>
          <el-divider direction="vertical" class="divider-margin" />
          <el-button text type="primary" @click="emialSet(row)">设置邮编</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
  <!-- 修改分区名称 -->
  <el-dialog
    v-model="openCityName"
    title="修改分区名称"
    width="250px"
    height="20px"
  >
    <el-form ref="nameFormRef" :model="countryForm" inline>
      <el-form-item prop="name" style="width: 150px;">
        <el-input
          v-model="countryForm.name"
          clearable
        ></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div>
        <el-button type="primary" @click="submitEditName">修改</el-button>
        <el-button @click="cancelEditName">取消</el-button>
      </div>
    </template>
  </el-dialog>
  <add-contry-partition ref="addContryPartitionRef" :product-id="props.basicInfo.id" @change-list="handleQuery"></add-contry-partition>
  <email-partition ref="emailPartitionRef"></email-partition>
</template>
<script lang="ts" setup>
import {
  ref,
  getCurrentInstance,
  defineAsyncComponent,
  watchEffect,
  h,
 
} from 'vue'
import { Delete, Edit, CirclePlus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox, ElButton } from 'element-plus'
import {
  addData,
  delData,
  editData,
  getData,
  addCodeList,
  delCodeList,
  getCodeList,
  batchCheckCountry,
  batchAddOrUpdate,
} from '@/api/BusinessConfig/costCountryPartition'
import { getQueryList } from '@/api/basicConfig/stateMaintanance'
import { uuid } from '@/utils/index'
import useDicts, { DictDirection } from '@/store/modules/dicts'

const InpValFormat = defineAsyncComponent(() => import('./InpValFormat.vue'))
const AddContryPartition = defineAsyncComponent(() => import('./AddContryPartition.vue'))
const EmailPartition = defineAsyncComponent(() => import('./EmailPartition.vue'))
const batchValue = ref<any[]>([])
const deleteMoreLoading = ref<boolean>(false)
const dicts = useDicts()
dicts.setDicts(DictDirection.方案类型)
const props = defineProps({
  basicInfo: {
    type: Object,
    default: () => ({}),
  },
})
const tableLoading = ref(false)
const addContryPartitionRef = ref(null)
const emailPartitionef = ref(null)
const openCityName = ref(false)
const tableData = ref([{}])
const multiple = ref(true)
const single = ref(true)
const batchAddLoading = ref<boolean>(false)
const countryForm = ref({ name: '' })
// 批量操作
interface batchCheck{
  name:string;
  countryName:string;
  planTypeId?:'1';
  costPriceId?:string;
  uuid?:string;
  id?:number;

}
// 批量操作判断数据是否为空
const isBatchValueEmpty = () => {
  if (!batchValue.value.length) {
    ElMessage.error('请输入数据!')
    return true
  }
  return false
}
// 检测国家是否重复并修改列表数据
const editProptyList = ['name', 'countryCode', 'countryNameEn', 'countryName']
const checkCountry = (params:batchCheck[], flag:boolean) => {
  batchAddLoading.value = true
  batchCheckCountry(params).then(({ code, data }) => {
    if (code !== 200) return 
    const { invalidCountryList, validCountryList } = data
    if (invalidCountryList && invalidCountryList.length !== 0) {
      const invalidStr = invalidCountryList.map(i => i.countryName).join('，')
      ElMessageBox.alert(`国家名：【${ invalidStr }】无效`)
    }

    /* 是否新增 如果有效国家长度大于0，则把有效国家添加入列表 */
    if (flag) {
      if (validCountryList.length !== 0) {
        tableData.value.push(...validCountryList)
      }
    } else {
      if (validCountryList.length === 0) return
      tableData.value.forEach(source => {
        validCountryList.forEach(country => {
          if (source.id == country.id) {
            editProptyList.forEach(key => {
              source[key] = country[key]
            })
          }
        })
      })
    }
    ElMessage.success('操作成功，如需保存请点击保存按钮')
  }).finally(() => {
    batchAddLoading.value = false
  })
}
// 检测重复
const isRepeat = () => {
  const countMap = {}
  batchValue.value.forEach(item => {
    if (countMap[item[1]] === undefined) {
      countMap[item[1]] = 1
    } else {
      countMap[item[1]]++
    }
  })
  const repeatData = Object.entries(countMap).filter(i => i[1] > 1)
  if (repeatData.length) {
    ElMessageBox({
      title: '温馨提示',
      message: h('div', null, [
        h('h3', null, '国家重复了'),
        ...repeatData.map(i => h('p', null, `${ i[0] }:${ i[1] }`)),
      ]),
      confirmButtonText: '确定',
    })
  }
}
// 批量新增
const batchAdd = () => {
  if (isBatchValueEmpty()) return
  // 判断重复
  isRepeat()
  const curUuid = uuid()
  const params:batchCheck[] = batchValue.value.map(item => ({
    name: item[0],
    countryName: item[1],
    planTypeId: '1',
    costPriceId: props.basicInfo.id,
    uuid: curUuid,
  }))
  checkCountry(params, true)
}
// 批量修改 
const batchEdit = () => {
  if (isBatchValueEmpty()) return
  isRepeat()
  if (batchValue.value.length > tableData.value.length) {
    // 超出处理
    batchValue.value.length = tableData.value.length
  }
  const params:batchCheck[] = batchValue.value.map((item, index) => ({
    name: item[0],
    countryName: item[1],
    id: tableData.value[index].id,
  }))
  checkCountry(params, false)
}
// 搜索
const handleQuery = () => {
  getList()
}
// 新增
const handleAdd = () => {
  addContryPartitionRef.value.countryOpen = true
}
// 方案类型过滤
const playTypeFormatter = (row) => {
  const obj = dicts[DictDirection.方案类型].find(item => item.dictValue === row.planTypeId)

  return obj && obj.dictLabel
}
let ids = []
// 多选框选中数据
const handleSelectionChange = (rows: { [key: string]: any }[]) => {
  const rowsList = JSON.parse(JSON.stringify(rows))
  ids = rowsList.map((item: { id: any }) => item.id)
  single.value = rowsList.length != 1
  multiple.value = !rowsList.length
}
// 删除国家分区
const handleDelete = (row) => {
  const id = row.id || ids
  deleteMoreLoading.value = true
  ElMessageBox.confirm('选中数据包括系统数据', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
  .then(() => delData(id))
  .then((res) => {
    if (res.code === 200) {
      handleQuery()
      ElMessage.success('删除成功')
    } else {
      ElMessage.error(res.msg)
    }
  })
  .catch((error) => {
    error === 'cancel' && ElMessage.info('取消操作')
  })
  .finally(() => {
    deleteMoreLoading.value = false
  })
}

/* 修改 */
// 关闭分区名称
const cancelEditName = () => {
  openCityName.value = false
}
const handleUpdate = () => {
  openCityName.value = true
  const data = { pageNum: 1, pageSize: 10, costPriceId: props.basicInfo.id }
  getData(data).then(res => {
    countryForm.value.name = res.data[0].name
  })
}
const submitEditName = () => {
  const data = { id: props.basicInfo.id, ...countryForm.value }
  editData(data).then(res => {
    res.code == 200 && handleQuery()
    openCityName.value = false
  })
}

const getList = () => {
  if (!props.basicInfo.id) return
  tableLoading.value = true
  const data = { costPriceId: props.basicInfo.id,
    pageSize: 10,
    pageNum: 1,
  }
  getData(data).then(res => {
    if (res.code === 200) {
      tableData.value = res.data || []
    }
  }).finally(() => {
    tableLoading.value = false
  })
}
// 设置邮编
const emialSet = (row) => {
  emailPartitionef.value.open(row.id)
}

// 初始化
watchEffect(getList)
// 保存
const save = () => batchAddOrUpdate(tableData.value).then(res => {
  if (res.code === 200) {
    ElMessage.success(res.msg)
    getList()
  }
})
defineExpose({
  save,
})
</script>
<style scoped lang="less">
.edit-box {
  margin-bottom: 16px;
  /deep/.el-textarea {
    width: 540px;
    margin-right: 20px;
    display: inline-block;
  }
  .edit-tips {
    font-family: "微软雅黑";
    font-size: 12px;
    color: #7a8298;
    line-height: 16px;
    margin: 4px 0 0;
  }
}
.btns-box {
  margin-bottom: 12px;
}
.divider-margin {
  margin: 0;
}
</style>
